package at.guigu.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    // 在原始方法（即目标方法）执行之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle Running...");
        String str = request.getParameter("param");
        if ("yes".equals(str)) {
            return true;
        } else {
            request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
            return false;
        }
    }

    // 在原始方法（即目标方法）执行之后，视图对象返回之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        modelAndView.addObject("username", "李四");
        System.out.println("postHandle Running...");
    }

    // 在整个请求完成之后执行（即在原始方法执行完并且视图对象也以返回之后执行）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion Running...");
    }
}
